package com.lc.wxauth.controller;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import cn.binarywang.wx.miniapp.bean.WxMaPhoneNumberInfo;
import cn.binarywang.wx.miniapp.bean.WxMaUserInfo;
import com.study.common.entity.bo.WxAuthBo;
import com.study.common.res.ApiResult;

import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import org.apache.commons.lang3.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.constraints.NotBlank;

/**
 * @description: some desc
 * @author: LChuang
 * @date: 2023/9/14 14:16
 */
@Slf4j
@RestController
@RequestMapping("/wx")
public class WxController {

    @Resource
    private WxMaService wxMaService;


    @PostMapping("/auth/login")
    public ApiResult login(@RequestBody @Validated WxAuthBo bo) {
        try {
            WxMaJscode2SessionResult sessionResult = wxMaService.getUserService().getSessionInfo(bo.getCode());
            // 获取openId、unionId、session_key
            String openid = sessionResult.getOpenid();
            String sessionKey = sessionResult.getSessionKey();
            String unionId = sessionResult.getUnionid();
            // TODO 可执行存库/修改用户信息等操作
        } catch (WxErrorException e) {
            log.error("通过微信code获取sessionResult异常：{}", e.getMessage());
        }
        return ApiResult.success();
    }



    /**
     * 用户使用手机号登陆
     * 接口的入参可根据情况调整，无sessionKey，可通过code获取
     */
    @PostMapping(value = "/auth/phone")
    public ApiResult wechatLogin(@RequestParam("code") @NotBlank(message = "sessionKey不能为空") String code,
                                 @RequestParam("sessionKey") @NotBlank(message = "sessionKey不能为空") String sessionKey,
                                 @RequestParam("encryptedData") @NotBlank(message = "加密串不能为空") String encryptedData,
                                 @RequestParam("iv") @NotBlank(message = "偏移串不能为空") String iv) {
        // 解析用户手机号
        String phone = parsePhone(sessionKey, encryptedData, iv);
        // 获取用户基本信息
        WxMaUserInfo userInfo = wxMaService.getUserService().getUserInfo(sessionKey, encryptedData, iv);
        // TODO 可执行存库/修改用户信息等操作
        return ApiResult.success(userInfo);
    }


    /**
     * 解析用户手机号
     *
     * @param sessionKey    sessionKey
     * @param encryptedData 加密串
     * @param iv            偏移串
     */
    private String parsePhone(String sessionKey, String encryptedData, String iv) {
        if (StringUtils.isEmpty(encryptedData) || StringUtils.isEmpty(iv) || StringUtils.isEmpty(sessionKey)) {
            return null;
        }
        String phone = null;
        try {
            // 1：根据session_key解析电话号码
            WxMaPhoneNumberInfo phoNumberInfo = wxMaService.getUserService().getPhoneNoInfo(sessionKey, encryptedData, iv);
            if (phoNumberInfo != null && phoNumberInfo.getPhoneNumber() != null) {
                phone = phoNumberInfo.getPhoneNumber();
            }
        } catch (Exception e) {
            log.error("【解析电话号码】异常:{}", e.getMessage());
        }
        return phone;
    }

}
